package com.xingdata.jjxc.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.xingdata.jjxc.App;
import com.xingdata.jjxc.R;
import com.xingdata.jjxc.RequestCode;
import com.xingdata.jjxc.base.Base1Activity;
import com.xingdata.jjxc.enty.RespEntity;
import com.xingdata.jjxc.enty.UserEntity;
import com.xingdata.jjxc.http.HttpResponseListener;
import com.xingdata.jjxc.m.login.avt.FindPwd1;
import com.xingdata.jjxc.utils.ActivityTools;
import com.xingdata.jjxc.utils.CameraUtils;
import com.xingdata.jjxc.utils.Code;
import com.xingdata.jjxc.utils.ImageUtils;
import com.xingdata.jjxc.utils.SP;
import com.xingdata.jjxc.utils.SystemInfo;
import com.xingdata.jjxc.views.CircleImageView;
import com.xingdata.jjxc.views.Widget;

/**
 * 我的资料，点击头像进入
 * 
 * @author ysc
 * 
 */
public class UserInfoActivity extends Base1Activity implements OnClickListener {
	final static String TAG = "UserInfoActivity";
	/** 头像 */
	private CircleImageView my_head_iv;
	private int flag;
	private Dialog dialog_camera, dialog_exit, dialog_login;
	// 拍照功能相关部分
	private final static String FILE_SAVEPATH = Environment.getExternalStorageDirectory().getAbsolutePath()
			+ "/zzd_goods/portrait/";
	protected Uri origUri;
	protected Uri cropUri;
	protected Bitmap pic;
	protected File protraitFile;
	protected String protraitPath;
	private TextView title;
	/**昵称*/
	private EditText name;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.user_info);
		ActivityTools.addActivities(this);
		initViews();
	}
	
	@Override
	protected void initViews() {
		name = (EditText) findViewById(R.id.name);
		name.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if(keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN){  
	                /*隐藏软键盘*/  
	                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  
	                if(inputMethodManager.isActive()){  
	                    inputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);  
	                }
	                
	                String nickName = name.getText().toString();
	    			doPost_modifyNickName(nickName);
	    			
	                return true;  
	            }
				return false;
			}
		});
		
		Typeface font = Typeface.createFromAsset(this.getAssets(), "fonts/PingFang-SC-Regular.ttf");
		
		my_head_iv = (CircleImageView) findViewById(R.id.my_head_iv);
		
		title = (TextView) findViewById(R.id.title);

		((TextView) findViewById(R.id.my_name_tv)).setTypeface(font);
		
		((TextView) findViewById(R.id.tv_phone)).setTypeface(font);
		((TextView) findViewById(R.id.name)).setTypeface(font);
		
		((TextView) findViewById(R.id.tv_nickname)).setTypeface(font);
		((TextView) findViewById(R.id.mobile)).setTypeface(font);
		
		((TextView) findViewById(R.id.modify_password)).setTypeface(font);
		((TextView) findViewById(R.id.modify_loginPwd)).setTypeface(font);
		((TextView) findViewById(R.id.login_out)).setTypeface(font);

		my_head_iv.setOnClickListener(this);
		((TextView) findViewById(R.id.login_out)).setOnClickListener(this);
		((LinearLayout) findViewById(R.id.modify_password_layout)).setOnClickListener(this);
	};
	
	/**
	 * 修改昵称
	 */
	private void doPost_modifyNickName(final String nickName){
		if (isNetworkConnected() == false) {
			showToast("网络连接断开，请检查网络");
			return;
		}
		paramsMap = new HashMap<String, String>();
		paramsMap.put("userid", SystemInfo.getUserInfo().getUserid());
		paramsMap.put("access_token", SystemInfo.getUserInfo().getToken());
		paramsMap.put("type", "username");
		paramsMap.put("username", nickName);
		mHttpUtil.Post(App.ZZD_REQUEST_UPDATEUSER, paramsMap, new HttpResponseListener() {
			
			@Override
			public void onSuccess(RespEntity respEntity) {
				// respEntity.getMsg() = ""
				showToast(respEntity.getMsg());
				Log.d(TAG, "onSuccess="+respEntity);
				Log.d(TAG, "onSuccess="+respEntity.getResult());
				Log.d(TAG, "更改成功后昵称1="+SystemInfo.getUserInfo().getUsername());
				SystemInfo.getUserInfo().setUsername(nickName);
			}
			
			@Override
			public void onLoading(int vurrent) {
				// TODO Auto-generated method stub
				Log.d(TAG, "onLoading="+vurrent);
			}
			
			@Override
			public void onFailure(String result) {
				// result = "秘钥匹配错误”
				showToast(result);
				Log.d(TAG, "onFailure ="+result);
			}
		});
	}

	private void initLoginView() {

		if (!SystemInfo.isLogin()) {
			Log.d(TAG, "log in");
			((TextView) findViewById(R.id.login_out)).setText("登录");
			name.setText("");
			((TextView) findViewById(R.id.mobile)).setText("");
			((LinearLayout) findViewById(R.id.modify_password_layout)).setVisibility(View.GONE);
		} else {
			Log.d(TAG, "log out");
			((TextView) findViewById(R.id.login_out)).setText("退出登录");
//			UserEntity entity = SystemInfo.getUserInfo();
			name.setText(SystemInfo.getUserInfo().getUsername());
			((TextView) findViewById(R.id.mobile)).setText(SystemInfo.getUserInfo().getMobile());
			if (SystemInfo.getUserInfo().getHead().contains("http://")) {
				App.imageLoader.displayImage(SystemInfo.getUserInfo().getHead(), my_head_iv, App.options);
			} else {
				App.imageLoader.displayImage(App.SEGMENTSOURCE + SystemInfo.getUserInfo().getHead(), my_head_iv,
						App.options);
			}
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login_out:
			if (SystemInfo.isLogin()) {
				exit();
			} else {
				startActivityForResult(new Intent(this, LoginActivity.class), RequestCode.REQUESTCODE_COMMON_LOGIN);
			}

			break;

		case R.id.my_head_iv:
			flag = 0;
			Widget.withDrawKeyboard(this);
			if (SystemInfo.isLogin()) {
				showPicDialog();
			} else {
				showLoginDialog();
			}

			break;

		case R.id.icon_l:
			setResult(RESULT_OK);
			finish();
			break;

		case R.id.modify_password_layout:
			startActivity(new Intent(UserInfoActivity.this, FindPwd1.class));
			break;
		default:
			break;
		}

	}

	private void showPicDialog() {
		if (dialog_camera == null) {
			dialog_camera = new Dialog(this, R.style.popup_fade_anim);

			// 设置显示动画
			Window window = dialog_camera.getWindow();
			window.setWindowAnimations(R.style.popup_fade_anim);
			WindowManager.LayoutParams wl = window.getAttributes();
			wl.x = 0;
			wl.y = getWindowManager().getDefaultDisplay().getHeight();
			window.setAttributes(wl);
			dialog_camera.onWindowAttributesChanged(wl);
			dialog_camera.setCanceledOnTouchOutside(true);

			View v = LayoutInflater.from(this).inflate(R.layout.popup_camera, null);
			View blank = v.findViewById(R.id.blank_view);

			blank.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog_camera.dismiss();
				}
			});
			LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
			dialog_camera.addContentView(v, params);

			Button shot = (Button) v.findViewById(R.id.shot);
			Button choose_from_piclib = (Button) v.findViewById(R.id.choose_from_piclib);
			Button cancel = (Button) v.findViewById(R.id.cancel);
			shot.setOnClickListener(listener);
			choose_from_piclib.setOnClickListener(listener);
			cancel.setOnClickListener(listener);
		}
		if (!this.isFinishing() && dialog_camera != null && !dialog_camera.isShowing()) {
			dialog_camera.show();
		}
	}

	private void showLoginDialog() {
		if (dialog_login == null) {
			dialog_login = new Dialog(this, R.style.popup_fade_anim);

			// 设置显示动画
			Window window = dialog_login.getWindow();
			window.setWindowAnimations(R.style.popup_fade_anim);
			WindowManager.LayoutParams wl = window.getAttributes();
			wl.x = 0;
			wl.y = getWindowManager().getDefaultDisplay().getHeight();
			window.setAttributes(wl);
			dialog_login.onWindowAttributesChanged(wl);
			dialog_login.setCanceledOnTouchOutside(true);

			View v = LayoutInflater.from(this).inflate(R.layout.popup_login, null);
			View blank = v.findViewById(R.id.blank_view);

			blank.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog_login.dismiss();
				}
			});
			LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
			dialog_login.addContentView(v, params);

			Button login = (Button) v.findViewById(R.id.login);
			Button cancel = (Button) v.findViewById(R.id.cancel);
			login.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					isLogin();
					dialog_login.dismiss();
				}
			});
			cancel.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dialog_login.dismiss();
				}
			});
		}
		if (!this.isFinishing() && dialog_login != null && !dialog_login.isShowing()) {
			dialog_login.show();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode != RESULT_OK) {
			return;
		}
		switch (requestCode) {
		case ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA:
			Intent crop = CameraUtils.startActionCrop(UserInfoActivity.this, origUri);
			startActivityForResult(crop, ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
			break;
		case ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD:
			Bundle bundle = data.getExtras();
			if (bundle != null) {
				Bitmap pic = bundle.getParcelable("data");
				Log.d(TAG, "从相册的来的图片="+pic);
				if (flag == 0) {
					my_head_iv.setImageBitmap(pic);
				}

				Bitmap bmpCompressed = Bitmap.createScaledBitmap(pic, 480, 480, true);
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				bmpCompressed.compress(CompressFormat.JPEG, 30, bos);
				byte[] byData = bos.toByteArray();

				File file = CameraUtils.getFile(byData, FILE_SAVEPATH, "pic.jpg");
				doPost_uploadImg(file);
			}

			break;

		case RequestCode.REQUESTCODE_COMMON_LOGIN:
			initLoginView();
			break;

		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private OnClickListener listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			/**
			 * 拍照
			 */
			case R.id.shot:
				startActionCamera();
				dialog_camera.dismiss();
				break;
			/**
			 * 从手机中获取照片
			 */
			case R.id.choose_from_piclib:
				startActivityForResult(CameraUtils.chooseImgActionCrop(UserInfoActivity.this),
						ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
				dialog_camera.dismiss();
				break;
			/**
			 * 退出
			 */
			case R.id.cancel:
				dialog_camera.dismiss();
				break;

			default:
				break;
			}
		}
	};

	/**
	 * 相机拍照
	 * 
	 * @param output
	 */
	private void startActionCamera() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, getCameraTempFile());
		startActivityForResult(intent, ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA);
	}

	/**
	 * 拍照保存的绝对路径
	 * 
	 * @return
	 */
	@SuppressLint("SimpleDateFormat")
	private Uri getCameraTempFile() {
		String storageState = Environment.getExternalStorageState();
		if (storageState.equals(Environment.MEDIA_MOUNTED)) {
			File savedir = new File(FILE_SAVEPATH);
			if (!savedir.exists()) {
				savedir.mkdirs();
			}
		} else {
			showToast("无法保存上传的头像，请检查SD卡是否挂载");
			return null;
		}
		String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		// 照片命名
		String cropFileName = "osc_camera_" + timeStamp + ".jpg";
		// 裁剪头像的绝对路径
		protraitPath = FILE_SAVEPATH + cropFileName;
		protraitFile = new File(protraitPath);
		cropUri = Uri.fromFile(protraitFile);
		this.origUri = this.cropUri;
		return this.cropUri;
	}

	/**修改头像*/
	private void doPost_uploadImg(File file) {
		if (isNetworkConnected() == false) {
			showToast("网络连接断开，请检查网络");
			return;
		}

		fileMap = new HashMap<String, Object>();

		fileMap.put("userid", SystemInfo.getUserInfo().getUserid());
		fileMap.put("type", "head");
		fileMap.put("image", file);
		// *****************************************************************************************************88
		String keyword = SystemInfo
				.getUserInfo()
				.getUserid()
				.substring(SystemInfo.getUserInfo().getUserid().length() - 1,
						SystemInfo.getUserInfo().getUserid().length())
				+ "0000";

		String keywordmd5 = Code.CodeMD5(Code.CodeMD5(keyword).toLowerCase()).toLowerCase();
		fileMap.put("keyword", keywordmd5);

		mHttpUtil.PostFile(App.ZZD_REQUEST_UPLOAD_IMG, fileMap, new HttpResponseListener() {

			@Override
			public void onSuccess(RespEntity respEntity) {
				Log.d(TAG, "onSuccess1="+respEntity);
				SystemInfo.getUserInfo().setHead(App.SEGMENTSOURCE + respEntity.getResult());
				SP.saveUserInfo(UserInfoActivity.this, SystemInfo.getUserInfo());

				if (SystemInfo.getUserInfo().getHead().contains("http://")) {
					App.imageLoader.displayImage(SystemInfo.getUserInfo().getHead(), my_head_iv, App.options);
				} else {
					App.imageLoader.displayImage(App.SEGMENTSOURCE + SystemInfo.getUserInfo().getHead(), my_head_iv,
							App.options);
				}
				
				paramsMap = new HashMap<String, String>();
				// paramsMap.put("access_token", Code.accessToken());
				paramsMap.put("userid", SystemInfo.getUserInfo().getUserid());
				paramsMap.put("access_token", SystemInfo.getUserInfo().getToken());
				paramsMap.put("type", "head");
				paramsMap.put("head", respEntity.getResult());
				Log.d(TAG, "1="+SystemInfo.getUserInfo().getHead());
				Log.d(TAG, "3="+respEntity.getResult());
				
				SystemInfo.getUserInfo().setHead(respEntity.getResult());
				
				mHttpUtil.Post(App.ZZD_REQUEST_CHANGEPWD, paramsMap, new HttpResponseListener() {

					@Override
					public void onSuccess(RespEntity respEntity) {
						// TODO Auto-generated method stub
						Log.d(TAG, "onSuccess2="+respEntity);
						showToast(respEntity.getMsg());
						App.imageLoader.displayImage(SystemInfo.getUserInfo().getHead(), my_head_iv, App.options);
						
					}

					@Override
					public void onLoading(int vurrent) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onFailure(String result) {
						showToast(result);
						Log.d(TAG, "1="+result);
					}
				});
			}

			@Override
			public void onLoading(int vurrent) {

			}

			@Override
			public void onFailure(String result) {
				showToast(result);
				Log.d(TAG, "2="+result);
			}
		});
	}

	/**
	 * 点击“退出登录”的确定与否的弹窗
	 */
	private void exit() {
		if (dialog_exit == null) {
			dialog_exit = new Dialog(this, R.style.my_dialog);
			// 通过inflate插入layout的方式，稍后试一下
			View v = LayoutInflater.from(this).inflate(R.layout.popup_exit, null);
			LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
			dialog_exit.addContentView(v, params);

			Typeface font = Typeface.createFromAsset(this.getAssets(), "fonts/PingFang-SC-Regular.ttf");
			View blank = v.findViewById(R.id.blank_view);

			TextView tv_judge = (TextView) v.findViewById(R.id.tv_judge);
			Button exit = (Button) v.findViewById(R.id.exit);
			Button cancel = (Button) v.findViewById(R.id.cancel_exit);
			
			tv_judge.setTypeface(font);
			exit.setTypeface(font);
			cancel.setTypeface(font);

			cancel.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dialog_exit.dismiss();
				}
			});

			exit.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					String strMobile = SystemInfo.getUserInfo().getMobile();
					UserEntity entity = new UserEntity();
					entity.setMobile(strMobile);
					SP.saveUserInfo(UserInfoActivity.this, entity);
					dialog_exit.dismiss();
					ActivityTools.startActivity(UserInfoActivity.this, new Intent(UserInfoActivity.this,
							LoginActivity.class));
					ActivityTools.finish();
				}
			});
			blank.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog_exit.dismiss();
				}
			});
		}
		if (!this.isFinishing() && dialog_exit != null && !dialog_exit.isShowing()) {
			dialog_exit.show();
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 如果是返回键,直接返回到桌面
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			setResult(RESULT_OK);
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	protected boolean isNetworkConnected() {

		ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

		cwjManager.getActiveNetworkInfo();
		boolean netSataus = true;
		if (cwjManager.getActiveNetworkInfo() == null) {

			netSataus = false;
		}
		return netSataus;
	}

	private boolean isLogin() {
		if (!SystemInfo.isLogin()) {
			startActivityForResult(new Intent(this, LoginActivity.class), RequestCode.REQUESTCODE_COMMON_LOGIN);
			return false;
		} else {
			return true;
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		initLoginView();

	}

	@Override
	protected int getContentViewId() {
		return R.layout.user_info;
	}

	@Override
	protected String getTitleText() {
		return "我的资料";
	}

}
